# -*- coding:utf-8 -*-
# Created by Jin(jinzhencheng@outlook.com) at 2018/9/18 12:10


from bd_spider.util import db_helper
from bd_spider.util import logger
from bd_spider.entity import HotNews
from datetime import datetime

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

__the_logger = logger.get_logger()
__mysql_helper = db_helper.MySQLHelper("bd_article_sys")

def inject(item):
    entity = HotNews()
    entity.id = 0
    entity.is_valid = 1
    entity.title = item["title"]
    entity.title_src = item["title_src"]
    entity.add_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    entity.trend = item["trend"]
    entity.type = item["type"]
    entity.type_src = item["type_src"]
    entity.search_count = item["search_count"]
    session = None
    try:
        __mysql_helper.open_driver()
        session = __mysql_helper.session
        session.add(entity)
        session.commit()
        __the_logger.info("Add ---- HotNews:title(%s), type(%s) into bd_article_sys.hot_news table" % (item["title"], item["type"]))
    except Exception, e:
        if session:
            session.rollback()
        __the_logger.error("Insert HotNews:title(%s),type(%s) into bd_article_sys.hot_news table error, detail: %s" % (item["title"], item["type"], e.message))

def set_invalid():
    session = None
    try:
        __mysql_helper.open_driver()
        session = __mysql_helper.session
        session.query(HotNews).update({HotNews.is_valid: 0})
        __the_logger.error("Update HotNews: All items have been set invalid" )
    except Exception, e:
        if session:
            session.rollback()
        __the_logger.error("Update HotNews: All items have been set invalid, error: %s" %  e.message)
